<template>
  <el-card>
    <div class="search-input-group">
      <el-form :model="searchForm" :inline="true">
        <el-form-item style="padding:5px" label="角色名称">
          <el-select 
            v-model="searchForm.roleName" 
            placeholder="请选择角色名称" 
            clearable
            filterable
          >
            <el-option
              v-for="item in roleOptions"
              :key="item.roleKey"
              :label="item.roleName"
              :value="item.roleName"
            />
          </el-select>
        </el-form-item>
        <el-form-item style="padding:5px" label="匹配方式">
          <el-select 
            v-model="searchForm.matchMethod" 
            placeholder="请选择匹配方式" 
            clearable
            filterable
          >
            <el-option
              label="精确匹配"
              value="exact"
            />
            <el-option
              label="前缀匹配"
              value="prefix"
            />
          </el-select>
        </el-form-item>
        <el-form-item style="padding:5px" label="菜单名称">
          <el-select 
            v-model="searchForm.menuName" 
            placeholder="请选择菜单名称" 
            clearable
            filterable
          >
            <el-option
              v-for="item in menuOptions"
              :key="item.menuId"
              :label="item.menuName"
              :value="item.menuName"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button @click="handleResetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="btn-group">
      <el-button 
        v-if="btnGroup.addb" 
        type="primary" 
        :icon="Plus"
        @click="showAddDialog"
      >
        添加
      </el-button>
      <el-button 
        v-if="btnGroup.editb" 
        type="success" 
        :icon="Edit"
        @click="showEditDialog"
        :disabled="multipleSelection.length !== 1"
      >
        修改
      </el-button>
      <el-button 
        v-if="btnGroup.deleteb" 
        type="danger" 
        :icon="Delete"
        @click="handleDelete"
        :disabled="multipleSelection.length <= 0"
      >
        删除
      </el-button>
    </div>
    <el-table 
      :data="dataList" 
      style="width: 100%" 
      row-key="rpId"
      @selection-change="handleSelectionChange"
      border
    >
      <el-table-column type="selection" width="40" />
      <el-table-column type="index" label="序号" width="80" show-overflow-tooltip/>
      <el-table-column prop="roleName" label="角色名称" show-overflow-tooltip/>
      <el-table-column prop="targetDesc" label="菜单名称" show-overflow-tooltip/>
      <el-table-column prop="requestUri" label="请求地址" show-overflow-tooltip />
      <el-table-column prop="matchMethod" label="匹配方式" show-overflow-tooltip />
      <el-table-column prop="operateStr" label="操作权限" show-overflow-tooltip>
        <template #default="scope">
          <el-tag v-if="scope.row.operateStr.includes('*')" type="success">全部权限</el-tag>
          <span v-else>
            <el-tag v-if="scope.row.operateStr.includes('a')" type="primary" style="margin-right: 5px;">增</el-tag>
            <el-tag v-if="scope.row.operateStr.includes('d')" type="danger" style="margin-right: 5px;">删</el-tag>
            <el-tag v-if="scope.row.operateStr.includes('u')" type="warning" style="margin-right: 5px;">改</el-tag>
            <el-tag v-if="scope.row.operateStr.includes('l')" type="info">查</el-tag>
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip />
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      :total="pagination.total"
      :page-sizes="[10, 20, 50]"
      layout="total, sizes, prev, pager, next"
      background
      @current-change="handleCurrentChange"
      class="pagination"
    />
  </el-card>
  
  <!-- 添加/修改角色权限的对话框 -->
  <el-dialog
    :title="dialogTitle"
    v-model="dialogVisible"
    width="500px"
    @close="handleDialogClose"
  >
    <el-form
      :model="operateDataForm"
      :rules="operateDataFormRules"
      ref="operateDataFormRef"
      label-width="100px"
    >
      <el-form-item v-if="!isEdit" label="角色" prop="roleId">
        <el-select 
          v-model="operateDataForm.roleId" 
          placeholder="请选择角色"
          style="width: 100%"
          filterable
        >
          <el-option
            v-for="item in roleOptions"
            :key="item.roleKey"
            :label="item.roleName"
            :value="item.roleId"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item v-if="!isEdit" label="菜单" prop="menuId">
        <el-select 
          v-model="operateDataForm.menuId" 
          placeholder="请选择菜单"
          style="width: 100%"
          filterable
        >
          <el-option
            v-for="item in menuOptions"
            :key="item.menuId"
            :label="item.menuName+'('+item.name+')'"
            :value="item.menuId"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item v-if="isEdit" label="角色" prop="roleId">
        <el-input 
          v-model="selectedRoleName" 
          placeholder="角色"
          disabled
        />
      </el-form-item>
      
      <el-form-item v-if="isEdit" label="菜单" prop="menuId">
        <el-input 
          v-model="selectedMenuName" 
          placeholder="菜单"
          disabled
        />
      </el-form-item>
      
      <el-form-item label="请求地址" prop="requestUri">
        <el-input 
          v-model="operateDataForm.requestUri" 
          placeholder="请输入请求地址"
        />
      </el-form-item>
      
      <el-form-item label="匹配方式" prop="matchMethod">
  <el-select 
    v-model="operateDataForm.matchMethod" 
    placeholder="请选择匹配方式"
    style="width: 100%"
    clearable
  >
    <el-option
      label="精确匹配"
      value="exact"
    />
    <el-option
      label="前缀匹配"
      value="prefix"
    />
  </el-select>
</el-form-item>
      
      <el-form-item label="操作权限" prop="operateStr">
        <el-input 
          v-model="operateDataForm.operateStr" 
          placeholder="请输入操作权限字符"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {
  Plus,
  Edit,
  Delete,
  Search
} from '@element-plus/icons-vue'
import { getList, getSearchList, add, edit, remove } from "@/api/management/rolePerms"
import { getListWithoutPage as roleList } from '@/api/management/role'
import { getListWithoutPage as menuList } from '@/api/management/menu'
import { onMounted, reactive, ref, computed } from "vue"
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'

// 模糊查询表单
const searchForm = reactive({
  roleName: '',
  menuName: '',
  matchMethod:''
})

// 对话框相关数据
const dialogVisible = ref(false)
const isEdit = ref(false)
const operateDataFormRef = ref(null)

// 添加或修改数据表单
const operateDataForm = reactive({
  rpId: '',
  roleId: null,
  menuId: null,
  requestUri: '',
  operateStr: '',
  matchMethod: ''
})

// 表单验证规则 - 根据是否为编辑模式动态调整必填规则
const operateDataFormRules = computed(() => {
  if (isEdit.value) {
    // 编辑模式下，roleId和menuId不需要验证（因为它们被隐藏了）
    return {
      requestUri: [
        { required: true, message: '请输入请求地址', trigger: 'blur' }
      ],
      operateStr: [
        { required: true, message: '请输入操作权限', trigger: 'blur' }
      ],
      matchMethod: [
        { required: true, message: '请选择匹配方式', trigger: 'change' }
      ]
    }
  } else {
    // 添加模式下，所有字段都需要验证
    return {
      roleId: [
        { required: true, message: '请选择角色', trigger: 'change' }
      ],
      menuId: [
        { required: true, message: '请选择菜单', trigger: 'change' }
      ],
      requestUri: [
        { required: true, message: '请输入请求地址', trigger: 'blur' }
      ],
      operateStr: [
        { required: true, message: '请输入操作权限', trigger: 'blur' }
      ],
      matchMethod: [
        { required: true, message: '请选择匹配方式', trigger: 'change' }
      ]
    }
  }
})

// 角色选项
const roleOptions = ref([])

// 菜单选项
const menuOptions = ref([])

// 选中的角色和菜单名称（仅用于编辑时展示）
const selectedRoleName = ref('')
const selectedMenuName = ref('')

// 对话框标题
const dialogTitle = computed(() => {
  return isEdit.value ? '修改角色权限' : '添加角色权限'
})

// 显示添加对话框
const showAddDialog = () => {
  isEdit.value = false
  dialogVisible.value = true
  // 重置表单
  Object.assign(operateDataForm, {
    roleId: null,
    menuId: null,
    requestUri: '',
    operateStr: '',
    matchMethod: ''
  })
}

// 显示编辑对话框
const showEditDialog = () => {
  isEdit.value = true
  dialogVisible.value = true
  // 填充表单数据
  const selected = multipleSelection.value[0]
  Object.assign(operateDataForm, {
    rpId: selected.rpId,
    roleId: selected.roleId,
    menuId: selected.menuId,
    requestUri: selected.requestUri,
    operateStr: selected.operateStr,
    matchMethod: selected.matchMethod
  })
  
  // 设置显示的角色和菜单名称
  selectedRoleName.value = selected.roleName
  selectedMenuName.value = selected.targetDesc
}

// 对话框关闭时的处理
const handleDialogClose = () => {
  operateDataFormRef.value?.resetFields()
}

// 固定参数源 ---start---
const userStore = useUserStore()
const dataList = ref([])
const multipleSelection = ref([])
const isSearch = ref(false)
const btnGroup = reactive({
  addb: false,
  editb: false,
  deleteb: false
})
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const getDataList = () => {
  let res = getList(pagination.currentPage)
  
  res.then(res => {
    dataList.value = res.data.records
    let opeStr = res.operateStr
    if(opeStr.includes("*") || opeStr.includes("a")) btnGroup.addb = true
    if(opeStr.includes("*") || opeStr.includes("d")) btnGroup.deleteb = true
    if(opeStr.includes("*") || opeStr.includes("u")) btnGroup.editb = true
    pagination.total = res.data.total
    pagination.pageSize = res.data.size
    pagination.currentPage = res.data.current
  })
}

const handleSearch = () => { 
  isSearch.value = true
  let res = getSearchList({
    ...searchForm
  }, pagination.currentPage)
  res.then(res => { 
    dataList.value = res.data.records
    pagination.total = res.data.total
    pagination.pageSize = res.data.size
    pagination.currentPage = res.data.current
  })
}

const handleResetSearch = () => { 
  searchForm.roleName = ""
  searchForm.menuName = ""
  isSearch.value = false
  handleSearch()
}

// 添加或修改数据操作提交
const submitForm = () => {
  console.log(operateDataForm.matchMethod)
  operateDataFormRef.value.validate(async (valid) => {
    if (valid) {
      if (isEdit.value) {
        // 编辑操作 - 仅传递需要的字段
        const { rpId,matchMethod, requestUri, operateStr } = operateDataForm
        await edit({ rpId,matchMethod, requestUri, operateStr })
      } else {
        // 添加操作 - 传递所有字段
        const { roleId,matchMethod, menuId, requestUri, operateStr } = operateDataForm
        await add({ roleId,matchMethod, menuId, requestUri, operateStr })
        
      }
      dialogVisible.value = false
      refreshList()
    }
  })
}

// 删除数据操作提交
const handleDelete = async () => {
  const ids = multipleSelection.value.map(item => item.rpId)
  await remove({ list: ids })
  refreshList()
}

const handleSelectionChange = (selection) => {
  multipleSelection.value = selection
}

// 当前页改变时触发
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  refreshList()
}

const refreshList = () => {
  if(isSearch.value) handleSearch()
  else getDataList()
}
// --- end ---

onMounted(() => {
  getDataList()
  let roles = roleList()
  roles.then(res => {
    roleOptions.value = res.data
  })
  
  // 获取菜单列表
  let menus = menuList()
  menus.then(res => {
    menuOptions.value = res.data
  })
})
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.btn-group {
  margin-bottom: 15px;
}

.btn-group .el-button {
  margin-right: 1px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.search-input-group {
  margin-bottom: 15px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.search-input-group .el-form-item {
  margin-bottom: 0;
  margin-right: 15px;
}
</style>